<template>
  <div class="home">
    <!-- 视频源选择下拉框 -->
    <div class="home--item">
      <span>视频源：</span>
      <select v-model="selectedVideoSource">
        <option
          v-for="source in videoSources"
          :key="source.deviceId"
          :value="source.deviceId"
        >
          {{ source.label }}
        </option>
      </select>
    </div>
    <!-- 姓名输入框 -->
    <div class="home--item">
      <span>姓名：</span>
      <input class="inp" v-model="name" placeholder="请输入姓名" />
    </div>
    <!-- 部位输入框 -->
    <div class="home--item">
      <span>部位：</span>
      <input class="inp" v-model="part" placeholder="请输入部位" />
    </div>
    <div class="home--item">
      <!-- 开始检查按钮 -->
      <button class="btn" @click="startRecording" :disabled="isRecording">
        开始检查
      </button>
      <!-- 结束检查按钮 -->
      <button class="btn" @click="stopRecording" :disabled="!isRecording">
        结束检查
      </button>
    </div>
    <!-- 视频预览 -->
    <video ref="videoPreview" autoplay muted></video>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "", // 姓名
      part: "", // 部位
      selectedVideoSource: "", // 选择的视频源设备ID
      videoSources: [], // 可用的视频源列表
      mediaStream: null, // 媒体流对象
      mediaRecorder: null, // 媒体录制器对象
      recordedChunks: [], // 录制的视频数据块
      isRecording: false, // 是否正在录制
    };
  },
  mounted() {
    this.getVideoSources();
  },
  methods: {
    // 获取可用的视频源
    async getVideoSources() {
    //   const constraints = {
    //     audio: false,
    //     video: true,
    //   };
    //   await navigator.mediaDevices.getUserMedia(constraints);
      const devices = await navigator.mediaDevices.enumerateDevices();
      console.log("devices", devices);
      this.videoSources = devices.filter(
        (device) => device.kind === "videoinput"
      );
      console.log("this.videoSources", this.videoSources);
    },
    // 开始录制
    async startRecording() {
      if (!this.name || !this.part) {
        alert("请输入姓名和部位！");
        return;
      }

      try {
        // 获取视频流
        const constraints = {
          video: {
            deviceId: this.selectedVideoSource
              ? { exact: this.selectedVideoSource }
              : undefined,
          },
        };
        this.mediaStream = await navigator.mediaDevices.getUserMedia(
          constraints
        );

        // 将视频流绑定到 video 标签进行预览
        this.$refs.videoPreview.srcObject = this.mediaStream;

        // 初始化 MediaRecorder
        this.mediaRecorder = new MediaRecorder(this.mediaStream, {
          mimeType: "video/webm",
        });

        // 监听数据可用事件
        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.recordedChunks.push(event.data);
          }
        };

        // 开始录制
        this.mediaRecorder.start();
        this.isRecording = true;
      } catch (error) {
        console.error("无法获取视频流：", error);
        alert("无法获取视频流，请检查摄像头权限！");
      }
    },

    // 停止录制
    stopRecording() {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.stop(); // 停止录制
        this.mediaStream.getTracks().forEach((track) => track.stop()); // 停止视频流
        this.isRecording = false;

        // 生成视频文件并下载
        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.recordedChunks, { type: "video/webm" });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `${this.name}_${
            this.part
          }_${new Date().toISOString()}.webm`;
          a.click();
          URL.revokeObjectURL(url); // 释放 URL 对象
          this.recordedChunks = []; // 清空录制的数据块
        };
      }
    },
  },
};
</script>

<style scoped>
.home {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 20px;
  box-sizing: border-box;
}
video {
  width: 600px;
  object-fit: contain;
  margin-top: 20px;
}
.home--item {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-bottom: 5px;
}
.inp {
  height: 30px;
  font-size: 20px;
}
.btn {
  font-size: 20px;
  margin-right: 10px;
}
</style>
